<script setup lang="ts">
  import { PropType, watch } from 'vue'
  import useUpdatePostingMsgPushNodeOaPersonService from '@/services/pages/base-info/useUpdatePostingMsgPushNodeOaPersonService'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import useOrganizeEmpListService from '@/services/module/organize/useOrganizeEmpListService'

  const {
    organizeEmpList,
    getOrganizeEmpListParam,
    getOrganizeEmpListLoading,
    getOrganizeEmpList,
  } = useOrganizeEmpListService()
  const {
    updatePostingMsgPushNodeOaPersonForm,
    updatePostingMsgPushNodeOaPersonLoading,
    updatePostingMsgPushNodeOaPerson,
    resetUpdatePostingMsgPushNodeOaPersonForm,
  } = useUpdatePostingMsgPushNodeOaPersonService()

  defineOptions({
    name: 'UpdatePostingMsgPushNodeOaPersonListModal',
  })

  const props = defineProps({
    msgPushNode: {
      type: Object as PropType<BaseInfoAPIResponse.PostingMsgPushNodeListItem>,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'update'): void
  }>()

  const visible = defineModel<boolean>('modelValue', { default: false })

  const onConfirmClick = async () => {
    const res = await updatePostingMsgPushNodeOaPerson()
    if (res) {
      if (res.code === 20000) {
        HMessage.success('更新成功')
        resetUpdatePostingMsgPushNodeOaPersonForm()
        emits('update')
        visible.value = false
        return
      }
      HMessageBox.error(res.message)
      return
    }

    HMessageBox.error('更新失败，请稍后重试')
  }

  const init = async () => {
    getOrganizeEmpListParam.value.limit = 10000
    await getOrganizeEmpList()
    updatePostingMsgPushNodeOaPersonForm.value = {
      empIds: props.msgPushNode.personnelVoList.map((item) => item.empId),
      pushMessageId: props.msgPushNode.id,
    }
  }

  watch(visible, (value) => {
    value && init()
  })
</script>

<template>
  <h-dialog
    v-model="visible"
    title="更新通知人员（OA）"
    :loading="updatePostingMsgPushNodeOaPersonLoading || getOrganizeEmpListLoading"
  >
    <el-form
      :model="updatePostingMsgPushNodeOaPersonForm"
      label-position="top"
      inline-message
      class="modal_form_content"
    >
      <el-form-item label="OA人员列表">
        <el-select
          v-model="updatePostingMsgPushNodeOaPersonForm.empIds"
          multiple
          placeholder="请选择OA人员"
        >
          <el-option
            v-for="(emp, empIndex) in organizeEmpList"
            :key="empIndex"
            :label="emp.name"
            :value="emp.empId"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <h-button is-modal type="primary" @click="onConfirmClick">确定</h-button>
      <h-button is-modal @click="visible = false">取消</h-button>
    </template>
  </h-dialog>
</template>
